<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/9/15
 * Time: 14:05
 */
namespace App\Api\Controllers\DaDa;


use App\Models\DadaOrder;
use App\Models\DadaStore;
use App\Models\MeituanpsConfigs;
use App\Models\MeituanpsOrders;
use App\Models\MeituanpsOrdersError;
use App\Models\MeituanpsStore;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CallBackController extends BaseController
{
    /**
     * 订单回调
     *
     * 每次订单状态发生变化时，会对添加订单接口中callback的URL进行回调。
     * 1. 已取消：包括配送员取消、商户取消、客服取消、系统取消（比如：骑士接单后一直未取货）， 此时订单的状态为5，可以通过“重新发单”来下发订单。
     * 2. 妥投异常：配送员在收货地，无法正常送到用户手中（包括用户电话打不通、客户暂时不方便收件、客户拒收、货物有问题等等）
     * 3. 状态1000：表示因为达达内部服务异常，导致下发订单失败。可以通过“新增订单”来下发订单
     * @param Request $request
     * @return string
     */
    public function callBackOrder(Request $request)
    {
        $data = $request->getContent();
        Log::info('达达配送订单状态回调');
        Log::info($data);

        try {
            if (isset($data)) {
                $data = json_decode($data, true);
                if (isset($data['order_id'])) {
                    $client_id = $data['client_id']; //返回达达运单号，默认为空
                    $order_id = $data['order_id']; //添加订单接口中的origin_id值
                    $order_status = $data['order_status']; //int 订单状态(待接单＝1,待取货＝2,配送中＝3,已完成＝4,已取消＝5, 指派单=8,妥投异常之物品返回中=9, 妥投异常之物品返回完成=10, 骑士到店=100,创建达达运单失败=1000 可参考文末的状态说明）
                    $cancel_reason = $data['cancel_reason']; //订单取消原因,其他状态下默认值为空字符串
                    $cancel_from = $data['cancel_from']; //int 订单取消原因来源(1:达达配送员取消；2:商家主动取消；3:系统或客服取消；0:默认值)
                    $update_time = $data['update_time']; //int 更新时间，时间戳除了创建达达运单失败=1000的精确毫秒，其他时间戳精确到秒
                    $signature = $data['signature']; //对client_id, order_id, update_time的值进行字符串升序排列，再连接字符串，取md5值
                    $dm_id = isset($data['dm_id']) ? $data['dm_id']: ''; //Int	否	达达配送员id，接单以后会传
                    $dm_name = isset($data['dm_name']) ? $data['dm_name']: ''; //否	配送员姓名，接单以后会传
                    $dm_mobile = isset($data['dm_mobile']) ? $data['dm_mobile']: ''; //否	配送员手机号，接单以后会传

                    $order_obj = DadaOrder::where('origin_id', $order_id)->first();
                    if ($order_obj) {
                        $update_data = [
                            'status_code' => $order_status
                        ];
                        if ($cancel_reason) $update_data['status_msg'] = $cancel_reason; //订单状态描述
                        if ($cancel_from) $update_data['message_type'] = $cancel_from; //消息类型
                        if ($update_time) $update_time = date('Y-m-d H:i:s', $update_time);
                        if ($order_status) {
                            if ($order_status == 3) {
                                if ($update_time) $update_data['accept_time'] = $update_time; //接单时间,若未接单,则为空
                            }
                            if ($order_status == 100) {
                                if ($update_time) $update_data['fetch_time'] = $update_time; //取货时间,若未取货,则为空
                            }
                            if ($order_status == 4) {
                                if ($update_time) $update_data['finish_time'] = $update_time; //送达时间,若未送达,则为空
                            }
                            if ($order_status == 5) {
                                if ($update_time) $update_data['cancel_time'] = $update_time; //取消时间,若未取消,则为空
                            }
                        }
                        $res = $order_obj->update($update_data);
                        if (!$res) {
                            Log::info($order_id.': 达达配送订单状态,更新失败');
                        }

                        //更新订单状态
                        //待接单-1,待取货-2,配送中-3,已完成-4,已取消-5,指派单-8,妥投异常之物品返回中-9,妥投异常之物品返回完成-10, 骑士到店-100,创建达达运单失败-1000

                        if(!empty($order_obj->out_trade_no) && isset($order_obj->out_trade_no)){
                            $customerAppletsUserOrderModel  = DB::table("customerapplets_user_orders")->where(['out_trade_no' => $order_obj->out_trade_no]);
                            $customerAppletsUserOrderResult = $customerAppletsUserOrderModel->first();
                            $nowDate = date("Y-m-d H:i:s",time());
                            if(!empty($customerAppletsUserOrderResult)){
                                switch ($order_status){
                                    case 1:

                                        break;
                                    case 2:
                                        if(!empty($dm_id)){
                                            $customerAppletsUserOrderModel->update([
                                                'dm_id'            => $dm_id,
                                                'dm_name'          => $dm_name,
                                                'dm_mobile'        => $dm_mobile,
                                                'order_pay_status' => 7,
                                                'updated_at'       => $nowDate
                                            ]);
                                        }else{
                                            $customerAppletsUserOrderModel->update([
                                                'order_pay_status' => 7,
                                                'updated_at'       => $nowDate
                                            ]);
                                        }

                                        break;
                                    case 3:
                                        if(!empty($dm_id)){
                                            $customerAppletsUserOrderModel->update([
                                                'dm_id'            => $dm_id,
                                                'dm_name'          => $dm_name,
                                                'dm_mobile'        => $dm_mobile,
                                                'order_pay_status' => 4,
                                                'updated_at'       => $nowDate
                                            ]);
                                        }else{
                                            $customerAppletsUserOrderModel->update([
                                                'order_pay_status' => 4,
                                                'updated_at'       => $nowDate
                                            ]);
                                        }
                                        break;
                                    case 4:
                                        $customerAppletsUserOrderModel->update([
                                            'order_pay_status' => 5,
                                            'updated_at'       => $nowDate
                                        ]);
                                        break;
                                    case 5:

                                        break;
                                    case 8:
                                        if(!empty($dm_id)){
                                            $customerAppletsUserOrderModel->update([
                                                'dm_id'            => $dm_id,
                                                'dm_name'          => $dm_name,
                                                'dm_mobile'        => $dm_mobile,
                                                'order_pay_status' => 8,
                                                'updated_at'       => $nowDate
                                            ]);
                                        }else{
                                            $customerAppletsUserOrderModel->update([
                                                'order_pay_status' => 8,
                                                'updated_at'       => $nowDate
                                            ]);
                                        }
                                        break;
                                    case 9:
                                        $customerAppletsUserOrderModel->update([
                                            'order_pay_status' => 9,
                                            'updated_at'       => $nowDate
                                        ]);
                                        break;
                                    case 10:
                                        $customerAppletsUserOrderModel->update([
                                            'order_pay_status' => 10,
                                            'updated_at'       => $nowDate
                                        ]);
                                        break;
                                    case 100:
                                        if(!empty($dm_id)){
                                            $customerAppletsUserOrderModel->update([
                                                'dm_id'            => $dm_id,
                                                'dm_name'          => $dm_name,
                                                'dm_mobile'        => $dm_mobile,
                                                'order_pay_status' => 100,
                                                'updated_at'       => $nowDate
                                            ]);
                                        }else{
                                            $customerAppletsUserOrderModel->update([
                                                'order_pay_status' => 100,
                                                'updated_at'       => $nowDate
                                            ]);
                                        }
                                        break;
                                    case 1000:
                                        $customerAppletsUserOrderModel->update([
                                            'order_pay_status' => 1000,
                                            'updated_at'       => $nowDate
                                        ]);
                                        break;
                                }
                            }
                        }

                    } else {
                        Log::info($order_id.': 达达配送-添加订单接口中的origin_id-未找到');
                    }

                    return json_encode(['status' => 'ok']);
                }
            }
            return json_encode(['status' => 'fail']);
        } catch (\Exception $ex) {
            Log::info('达达配送订单状态回调error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return json_encode([
                'status' => -1,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


    /**
     * 骑士取消订单 回调
     *
     * 1.骑士取消订单后，达达开放平台推送消息至商家配置的URL
     * 2.商家接收到消息后，进行确认操作
     * @param Request $request
     * @return string
     */
    public function callBackReturnStatus(Request $request)
    {
        $data = $request->getContent();
        Log::info('达达配送-骑士取消订单-回调');
        Log::info($data);

        try {
            if (isset($data)) {
                $data = json_decode($data, true);
                if (isset($data['orderId'])) {
                    $orderId = $data['orderId']; //String	是	商家第三方订单号
                    $dadaOrderId = isset($data['dadaOrderId']) ? $data['dadaOrderId']: ''; //long	否	达达订单号
                    $cancelReason = $data['cancelReason']; //String	是	骑士取消原因

                    $order_obj = DadaOrder::where('origin_id', $orderId)->first();
                    if (!$order_obj && $dadaOrderId) {
                        $order_obj = DadaOrder::where('dada_order_id', $dadaOrderId)->first();
                    }
                    if ($order_obj) {
                        $update_data = [
                            'status_code' => 5,
                            'status_msg' => $cancelReason,
                            'message_type' => 1
                        ];
                        $res = $order_obj->update($update_data);
                        if (!$res) {
                            Log::info($data['orderId'].': 达达配送-骑士取消订单回调-更新失败');
                        }
                    } else {
                        Log::info($data['orderId'].': 达达配送-骑士取消订单回调-添加订单接口中的origin_id-未找到');
                    }

                    return json_encode(['status' => 'ok']);
                }
            }
            return json_encode(['status' => 'fail']);
        } catch (\Exception $ex) {
            Log::info('达达配送订单状态回调error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return json_encode([
                'status' => -1,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ]);
        }
    }


}
